package cn.broadin.app.hotel.component;


import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.File;

import cn.broadin.app.hotel.HomeActivity;
import cn.broadin.app.hotel.app.AppConfig;
import cn.broadin.app.hotel.app.AppContext;
import cn.broadin.app.hotel.dialog.DownLoadDialog;
import cn.broadin.app.hotel.task.AppDownloadTask;
import cn.broadin.app.hotel.task.DownLoadTask;
import cn.broadin.app.hotel.util.PDUtils;
import cn.broadin.app.hotel.util.XLog;
import cn.broadin.app.hotel.util.XToast;
import cn.broadin.app.hotel.util.XUIHelper;
import cn.broadin.app.hotel.util.XUtils;

public abstract class BaseView<E extends BaseViewData> implements View.OnClickListener, View.OnFocusChangeListener{

    protected Context mContext;

    protected E mData;

    protected View mParentView;

    public BaseView(Context context, E data){
        this.mContext = context;
        this.mData = data;
    }

    /**
     * 创建视图
     * @param rootView
     */
    public void onCreate(RelativeLayout rootView, RelativeLayout rootView2){
        mParentView = onCreateView(rootView);
        RelativeLayout.LayoutParams layoutParams = initViewLayoutParams(rootView, mParentView, mData);
        if(mData.zindex == 1){
            rootView2.addView(mParentView, layoutParams);
        } else {
            rootView.addView(mParentView, layoutParams);
        }
    }

    /**
     * 创建视图
     * @param rootView
     * @return
     */
    protected abstract View onCreateView(RelativeLayout rootView);

    /**
     * 初始化视图样式参数
     * @param rootView
     * @param parentView
     * @param data
     * @return
     */
    protected RelativeLayout.LayoutParams initViewLayoutParams(RelativeLayout rootView,
                                                               View parentView, E data){
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                getMeasuredPx(data.width), getMeasuredPx(data.height));
        layoutParams.leftMargin = getMeasuredPx(data.left);
        layoutParams.topMargin = getMeasuredPx(data.top);
        // 是否允许点击
        if(data.clickable){
            parentView.setOnClickListener(this);
        }
        // 是否获取焦点
        if(data.focusable){
            parentView.setFocusable(true);
            parentView.setFocusableInTouchMode(true);
            parentView.setOnFocusChangeListener(this);
        }

        return layoutParams;
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 是否允许获取焦点
     * @return
     */
    public boolean isFocusable(){
        return mData.focusable;
    }

    /**
     * 获取焦点
     */
    public void requestFocus(){
        mParentView.requestFocus();
    }

    public void onResume() {
    }

    public void onPause() {
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        /**if(hasFocus){
            int[] location = new int[2];
            int left, top, width, height;
            v.getLocationInWindow(location);

            left = (int) (location[0] - XUtils.getDimension(mContext, R.dimen.px36));
            top = (int) (location[1] - XUtils.getDimension(mContext, R.dimen.px36));
            width = (int) (v.getWidth() + XUtils.getDimension(mContext, R.dimen.px72));
            height = (int) (v.getHeight() + XUtils.getDimension(mContext, R.dimen.px72));

            XLog.i("onFocusChange: left: " + left + ", top: " + top + ", width: " + width + ", height: " + height);

            View focusImageView = ((HomeActivity)mContext).getFoucsImageView();
            if(focusImageView == null){
                return;
            }
            TvAnimator animator = new TvAnimator(focusImageView, v);
            animator.setTargetParams(left, top, width, height);
            animator.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }*/
    }

    public void onDestroy(){

    }

    public int getMeasuredPx(Integer px){
        if(px == null){
            return -1;
        }
        if(px == 0){
            return -2;
        }
        DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        XLog.i("screenWidth:" + screenWidth);
        px = (int)((screenWidth / 1920f ) * px);
//        float scale = mContext.getResources().getDisplayMetrics().density;
//        return (int) (px / scale + 0.5f);
        return px;
    }

    public String getValue(String val, String defaultVal){
        if(TextUtils.isEmpty(val)){
            return defaultVal;
        } else {
            return val;
        }
    }

    public Context getContext(){
        return mContext;
    }

    public E getData(){
        return mData;
    }

    /**
     * 启动界面
     * @param intent
     */
    public void startActivity(Intent intent){
        mContext.startActivity(intent);
    }


    /**
     * 跳转进入其他界面
     * @param data
     */
    public void jumpToOtherActivity(BaseViewData data){
        if(data == null){
            return;
        }
        jumpToOtherActivity(data.authable, data.link, data.slink, data.params);
    }

    /**
     * 跳转进入其他界面
     * @param type
     * @param params
     */
    public void jumpToOtherActivity(boolean isAuth, Byte type, Byte stype, String params){
        if(type == null){
            return;
        }
        if(isAuth && !AppContext.getInstance().deviceAuthFlag){
            XToast.makeText(mContext, "此业务未开通，请联系运营商开通").show();
            return;
        }
        try{
            switch(type){
                case BaseViewData.TYPE_OPEN_HTTP:
                    // 打开浏览器
                    break;
                case BaseViewData.TYPE_START_APP:
                    // 启动第三方app
                    openThirdApp(getContext(), params);
                    break;
                case BaseViewData.TYPE_START_ACTIVITY:
                    // 启动内置界面
                    openStartActivity(type, stype, params);
                    break;
                default:
            }
        } catch(Exception e){
            e.printStackTrace();
            XToast.makeText(mContext, "应用启动失败！").show();
        }
    }

    private final static String SVAE_DIR = "/mnt/sdcard/";  //AMlogic芯片方案存放路径


    /**
     * 启动内置第三方APP
     * @param params
     */
    public void openThirdApp(final Context context, String params){
        // 判断APK是否已经安装
        JSONObject jsonObject = JSON.parseObject(params);
        String pkg = jsonObject.getString("pkg");
        String cls = jsonObject.getString("cls");
        openThirdApp(context, pkg, cls);
    }

    /**
     * 启动内置第三方APP
     * @param context
     * @param pkg
     * @param cls
     */
    public void openThirdApp(final Context context, String pkg, String cls){
        // 判断APK是否已经安装
        boolean isInstalled = XUtils.isAppInstalled(context, pkg);
        if(isInstalled){
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(pkg, cls));
            intent.setAction("android.intent.action.MAIN");
            intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);
            Bundle mbundle = new Bundle();
            mbundle.putString("authAddress",AppConfig.roomUrl);
            mbundle.putString("versionCode",AppConfig.versionCode);
            intent.putExtras(mbundle);
            startActivity(intent);
        } else {
            // 判断是否在下载中
            boolean isDownloading = checkAppIsDownloading(context, pkg, cls);
            if(isDownloading){
                XToast.makeText(context, "应用正在下载中").show();
            } else {
                // 触发下载逻辑
                final String fileName = System.currentTimeMillis() + ".apk";
                final String url = AppConfig.SERVER_BASH_URL + "/" + pkg + ".apk";
                new AppDownloadTask((Activity) context, new AppDownloadTask.AddListener(){
                    @Override
                    public void onSuccess() {
                        installApp(new File(SVAE_DIR, fileName), context);
                    }
                }).execute(new String[]{url, SVAE_DIR, fileName});
            }
        }
    }

    /**
     * 安装App
     * @param file
     * @param context
     */
    private void installApp(File file, Context context){
        try{
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);				//执行动作
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");	//执行的数据类型
            context.startActivity(intent);
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 判断app是否正在下载中
     * @param context
     * @param pkg
     * @return
     */
    private boolean checkAppIsDownloading(Context context, String pkg, String cls){
        return false;
    }

    /**
     * 根据子类型打开页面
     * @param type
     * @param stype
     * @param params
     */
    protected void openStartActivity(Byte type, Byte stype, String params){
        if(stype == null){
            return;
        }
        switch(stype){
            case BaseViewData.STYPE_SETTYINGS:
                XUIHelper.openPasswordActivity((HomeActivity) mContext);
                break;
        }
    }
}
